package com.example.protocol;

import com.example.message.Message;
import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;

public interface Serializer {

    <T> T deserializer(Class<T> tClass, byte[] bytes);

    <T> byte[] serializer(T object);

    enum Algo implements Serializer {
        Java {
            @Override
            public <T> T deserializer(Class<T> tClass, byte[] bytes) {

                ObjectInputStream ois = null;
                try {
                    ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
                    Message message = (Message) ois.readObject();
                    return (T) message;
                } catch (Exception e) {
                    throw new RuntimeException("反序列化失败");
                }
            }

            @Override
            public <T> byte[] serializer(T object) {

                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(bos);
                    oos.writeObject(object);
                    return bos.toByteArray();
                } catch (Exception e) {
                    throw new RuntimeException("序列化失败");
                }

            }
        },
        Json {
            @Override
            public <T> T deserializer(Class<T> tClass, byte[] bytes) {
                String s = new String(bytes, StandardCharsets.UTF_8);
                return new Gson().fromJson(s, tClass);
            }

            @Override
            public <T> byte[] serializer(T object) {
                String s = new Gson().toJson(object);
                return s.getBytes(StandardCharsets.UTF_8);
            }
        }
    }
}
